<?php

namespace Addons\OaSystem\Controller;
use Think\ManageBaseController;

class OaEmployeeController extends OaBaseController {
    protected $model;
    protected $token;
    function _initialize() {
        $this->model = $this->getModel ( 'oa_employee' );
        $this->token = get_token();

        parent::_initialize ();

        $controller = strtolower ( CONTROLLER_NAME );

        $res ['title'] = '员工信息';
        $res ['url'] = addons_url ( 'OaSystem://OaEmployee/lists' ,array('mdm'=>I('mdm')));
        $res ['class'] = $controller == 'OaEmployee' ? 'current' : '';
        $nav [] = $res;

        $this->assign ( 'nav', $nav );
    }

    public function lists(){
        $res['title'] = '批量录入';
        $res['is_buttion'] = false;
        $res['url'] = addons_url ( 'OaSystem://OaEmployee/import' ,array('mdm'=>I('mdm')));
        $top_more_button[] = $res;
        $res['title'] = 'excel 导出';
        $res['is_buttion'] = false;
        $res ['url'] = addons_url ( 'OaSystem://OaEmployee/export' ,array('mdm'=>I('mdm')));
        $top_more_button[] =$res;

        $this->assign('top_more_button',$top_more_button);
        $this->assign('add_button',true);

        $list_data = $this->_get_model_list ( $this->model );
        $grids = $list_data['list_grids'];
        $data = db_select('oa_employee');
        foreach ($data as $i => $v) {
            $dept = db_find('oa_dept', ['id'=>$v['dept_id']]);
            $pdept = db_find('oa_dept', ['id'=>$dept['pid']]);
            $duty = db_find('oa_duty', ['id'=>$v['duty_id']]);
            $adminLvl = db_find('oa_emp_admin_level', ['id'=>$v['adminLvl_id']]);
            
            $data[$i]['dept_id'] = ($dept['dept_grade_id']==3)?($pdept['name'].'_'.$dept['name']):$dept['name'];
            $data[$i]['duty_id'] = end(explode('_', $duty['name']));
            $data[$i]['adminLvl_id'] = $adminLvl['name'];
            $data[$i]['mobile_list'] = implode(', ', json_decode($v['mobile_list'],true));

            $editUrl = U('edit', array('id'=> $v['id']));
            $delUrl = U('del', array('id'=> $v['id']));
            $resetpsdUrl = "javascript:if(confirm('确认重置该员工的密码?'))location='".U('resetpsd', array('id'=> $v['id']))."'";
            $data[$i]['urls'] = "<a href=$editUrl>编辑</a>".'   '."<a class='confirm' href=$delUrl>删除</a>".'   '."<a href=$resetpsdUrl>重置密码</a>";
        }
        $this->assign('list_grids', $grids);
        $this->assign('list_data', $data);
        $this->display();
    }

    public function details(){
        $this->display();
    }

    public function add() {
        if(IS_POST) {
            $data['appid'] = $this->appId;
            $data['emp_no'] = $_POST['emp_no'];
            $data['name'] = $_POST['name'];
            $data['account'] = $_POST['emp_no'];
            $data['password'] = '123456';
            $data['adminLvl_id'] = $_POST['adminLvl_id'];
            $data['sex'] = $_POST['sex'];
            $data['birthday'] = $_POST['birthday'];
            $data['office_tel'] = $_POST['office_tel'];
            $data['create_time'] = date('y-m-d h:i:s', time());
            $data['idnum'] = $_POST['idnum'];
            $data['mobile_list'] = $_POST['mobile_list'];

            if($_POST['button_cancel']==1) {
                $url = addons_url('OaSystem://OaEmployee/lists', array('mdm' => I('mdm'), 'type'=>$application['type'], 'subtype'=>$application['subtype'], 'application_id'=>$data['application_id']));
                redirect($url);
            }

            $itemName = array(
                'emp_no' => '员工编号',
                'name' => '员工姓名',
                'account' => '用户名',
                'duty_id' => '职务',
                'adminLvl_id' => '行政级别',
                'sex' => '性别',
                'birthday' => '出生年月',
                'idnum' => '身份证号',
                'mobile_list' => '手机号'
            );
            foreach ($data as $key => $v) {
                if(empty($v) &&
                    ($key != 'office_tel' &&
                        $key != 'birthday' &&
                        $key != 'sex'))  {
                    $this->error($itemName[$key].' 没有输入, 请输入！');
                    return false;
                }
            }

            $dutyname = $this->dutylist[$_POST['duty_id']];
            if(empty($_POST['chu_dept_id']) && !in_array($dutyname, $this->leaderDutys['guan'])) {
                $this->error('请选择处室！');
                return false;
            }
            $chu_dept = db_find('oa_dept', ['id'=>$_POST['chu_dept_id']]);
            $ke_dept = db_find('oa_dept', ['id'=>$_POST['ke_dept_id']]);
            if(empty($_POST['ke_dept_id'])) {
                if(in_array($dutyname, $this->leaderDutys['chu'])) {
                    $dutyname = $chu_dept['name'].'_'.$dutyname;
                } else if(in_array($dutyname, $this->leaderDutys['ke'])) {
                    $this->error('科级副科级领导需要选择科室！');
                    return false;
                }
            } else {
                if(in_array($dutyname, $this->leaderDutys['ke'])) {
                    $dutyname = $chu_dept['name'].'_'.$ke_dept['name'].'_'.$dutyname;
                } else if(in_array($dutyname, $this->leaderDutys['chu'])) {
                    $this->error('处级副处级领导无需选择科室, 请重新输入！');
                    return false;
                }
            }
            if(($duty = db_find('oa_duty', ['name'=>$dutyname])) == NULL) {
                $this->error('找不到职务 - '.$dutyname.', 请检查！');
                return false;
            }
            $data['duty_id'] = $duty['id'];

            if(in_array($dutyname, $this->leaderDutys['guan'])) {
                $guan_dept = db_find('oa_dept', ['dept_grade_id'=>1]);
                $data['dept_id'] = $guan_dept['id'];
            } else {
                $data['dept_id'] = empty($_POST['ke_dept_id'])?$_POST['chu_dept_id']:$_POST['ke_dept_id'];
            }

            if(db_find('oa_employee', ['name'=>$data['name'], 'idnum'=>$data['idnum'], 'is_left'=>0])) {
                $this->error('该员工已经存在, 请重新输入！');
                return false;
            }

            if(db_find('oa_employee', ['emp_no'=>$data['emp_no'], 'is_left'=>0])) {
                $this->error('该员工编号已经使用， 请重新输入！');
                return false;
            }

            if(empty($data['dept_id']) || empty($data['duty_id']) ||empty($data['adminLvl_id'])) {
                $this->error('部门或者职务或者级别选择错误， 请重新输入！');
                return false;
            }

            if(!db_find('oa_role_duty', ['duty_id'=>$data['duty_id']])) {
                $this->error('找不到该职务的角色关系表， 请先输入职务角色关系表！');
                return false;
            }

            $mobile_array = explode(";", $_POST['mobile_list']);
            if(empty($mobile_array)) {
                $this->error('手机号码格式错误， 请重新输入！');
                return false;
            }

            $data['mobile_list'] = json_encode($mobile_array);
            $data['is_left'] = 0;
            $sameAccounts = M('OaEmployee')->where(array('account'=>$data['account']))->select();
            if ($sameAccounts != NULL && $sameAccounts[0]['idnum'] != $data['idnum']) {
                $this->error('添加员工信息表失败！登录名重复！！');
                return false;
            }
            if(M('oa_employee')->where(['name'=>$data['name'], 'idnum'=>$data['idnum']])->find()) {
                db_save('oa_employee', ['name'=>$data['name'], 'idnum'=>$data['idnum']], $data);
            } else {
                $emp_id = M('oa_employee')->add($data);
                if($emp_id == false) {
                    $this->error('添加员工信息表失败！');
                    return false;
                }
            }

            //update oa_user_employee
            $user_emp_data['appid'] = $this->appId;
            $user_emp_data['emp_id'] = $emp_id;
            $user_emp_data['mobile_array'] = $mobile_array;
            $user_emp_data['time'] = date('y-m-d h:i:s', time());
            if(D('OaUserEmployee')->addUserEmployee($user_emp_data) == false) {
                $this->error('addUserEmployee 失败！');
                return false;
            }

            //update oa_user_role
            $dutyRoles = db_select('oa_role_duty', ['duty_id'=>$data['duty_id']]);
            foreach ($dutyRoles as $v) {
                $user_role['appid'] = $this->appId;
                $user_role['emp_id'] = $emp_id;
                $user_role['role_id'] = $v['role_id'];
                $user_role['assigned_by'] = 0;
                if(M('oa_user_role')->add($user_role) == false) {
                    $this->error('add oa_user_role 失败！');
                    return false;
                }
            }

            $this->success ( '创建' . $model ['title'] . '成功！', U ( 'lists?model=' . $model ['name'], $this->get_param ));

        } else {
            $chu_depts = db_select('oa_dept', ['dept_grade_id'=>2]);
            foreach ($this->dutylist  as $i => $v) {
                $duty[$i]['id'] = $i;
                $duty[$i]['name'] = $v;
            }
            $adminLvl = db_select('oa_emp_admin_level');
            $ke_depts = db_select('oa_dept', ['dept_grade_id'=>3]);
            $ke_depts = json_encode($ke_depts, JSON_UNESCAPED_UNICODE);
            $ke_depts = str_replace('"','&quot;', $ke_depts);

            array_unshift($chu_depts, array('id'=>0, 'name'=>''));
            $this->assign('chu_depts', $chu_depts);
            $this->assign('ke_depts', $ke_depts);
            $this->assign('duty', $duty);
            $this->assign('adminLvl', $adminLvl);
            $this->display('add');
        }
    }

    public function edit(){
        if(IS_POST) {
            $data['appid'] = $this->appId;
            $data['emp_no'] = $_POST['emp_no'];
            $data['name'] = $_POST['name'];
            $data['adminLvl_id'] = $_POST['adminLvl_id'];
            $data['sex'] = $_POST['sex'];
            $data['birthday'] = $_POST['birthday'];
            $data['office_tel'] = $_POST['office_tel'];
            $data['create_time'] = date('y-m-d h:i:s', time());
            $data['idnum'] = $_POST['idnum'];
            $data['mobile_list'] = $_POST['mobile_list'];
            $emp_id = $_POST['id'];

            if($_POST['button_cancel']==1) {
                $url = addons_url('OaSystem://OaEmployee/lists', array('mdm' => I('mdm'), 'type'=>$application['type'], 'subtype'=>$application['subtype'], 'application_id'=>$data['application_id']));
                redirect($url);
            }

            $itemName = array(
                'emp_no' => '员工编号',
                'name' => '员工姓名',
                'account' => '用户名',
                'duty_id' => '职务',
                'adminLvl_id' => '行政级别',
                'sex' => '性别',
                'birthday' => '出生年月',
                'idnum' => '身份证号',
                'mobile_list' => '手机号'
            );
            foreach ($data as $key => $v) {
                if(empty($v) &&
                    ($key != 'office_tel' &&
                        $key != 'birthday' &&
                        $key != 'sex'))  {
                    $this->error($itemName[$key].' 没有输入, 请输入！');
                    return false;
                }
            }

            $dutyname = $this->dutylist[$_POST['duty_id']];
            if(empty($_POST['chu_dept_id']) && !in_array($dutyname, $this->leaderDutys['guan'])) {
                $this->error('请选择处室！');
                return false;
            }
            $chu_dept = db_find('oa_dept', ['id'=>$_POST['chu_dept_id']]);
            $ke_dept = db_find('oa_dept', ['id'=>$_POST['ke_dept_id']]);
            if(empty($_POST['ke_dept_id'])) {
                if(in_array($dutyname, $this->leaderDutys['chu'])) {
                    $dutyname = $chu_dept['name'].'_'.$dutyname;
                } else if(in_array($dutyname, $this->leaderDutys['ke'])) {
                    $this->error('科级副科级领导需要选择科室！');
                    return false;
                }
            } else {
                if(in_array($dutyname, $this->leaderDutys['ke'])) {
                    $dutyname = $chu_dept['name'].'_'.$ke_dept['name'].'_'.$dutyname;
                } else if(in_array($dutyname, $this->leaderDutys['chu'])) {
                    $this->error('处级副处级领导无需选择科室, 请重新输入！');
                    return false;
                }
            }
            if(($duty = db_find('oa_duty', ['name'=>$dutyname])) == NULL) {
                $this->error('找不到职务 - '.$dutyname.', 请检查！');
                return false;
            }
            $data['duty_id'] = $duty['id'];
            
            if(in_array($dutyname, $this->leaderDutys['guan'])) {
                $guan_dept = db_find('oa_dept', ['dept_grade_id'=>1]);
                $data['dept_id'] = $guan_dept['id'];
            } else {
                $data['dept_id'] = empty($_POST['ke_dept_id'])?$_POST['chu_dept_id']:$_POST['ke_dept_id'];
            }

            if(empty($data['dept_id']) || empty($data['duty_id']) ||empty($data['adminLvl_id'])) {
                $this->error('部门或者职务或者级别选择错误， 请重新输入！');
                return false;
            }

            if(!db_find('oa_role_duty', ['duty_id'=>$data['duty_id']])) {
                $this->error('找不到该职务的角色关系表， 请先输入职务角色关系表！');
                return false;
            }

            $mobile_array = explode(";", $_POST['mobile_list']);
            if(empty($mobile_array)) {
                $this->error('手机号码格式错误， 请重新输入！');
                return false;
            }

            $data['mobile_list'] = json_encode($mobile_array);
            $data['is_left'] = 0;
            $sameAccounts = M('OaEmployee')->where(array('account'=>$data['account']))->select();
            if ($sameAccounts != NULL && $sameAccounts[0]['idnum'] != $data['idnum']) {
                $this->error('添加员工信息表失败！登录名重复！！');
                return false;
            }

            if(($employee = db_find('oa_employee', ['id'=>$emp_id])) == NULL) {
                $this->error('找不到该员工信息，请检查！');
                return false;
            }
            
            db_save('oa_employee', ['id'=>$emp_id], $data);

            //update oa_user_employee
            if($employee['mobile_list'] != $data['mobile_list']) {
                $user_emp_data['appid'] = $this->appId;
                $user_emp_data['emp_id'] = $emp_id;
                $user_emp_data['mobile_array'] = $mobile_array;
                $user_emp_data['time'] = date('y-m-d h:i:s', time());
                if (D('OaUserEmployee')->addUserEmployee($user_emp_data) == false) {
                    $this->error('addUserEmployee 失败！');
                    return false;
                }
            }

            //update user_role if needed
            if($employee['duty_id'] != $data['duty_id']) {
                $map['appid'] = $this->appId;
                $map['emp_id'] = $emp_id;
                M('oa_user_role')->where($map)->delete();
                $dutyRoles = db_select('oa_role_duty', ['duty_id'=>$data['duty_id']]);
                foreach ($dutyRoles as $v) {
                    $user_role['appid'] = $this->appId;
                    $user_role['emp_id'] = $emp_id;
                    $user_role['role_id'] = $v['role_id'];
                    $user_role['assigned_by'] = 0;
                    if(M('oa_user_role')->add($user_role) == false) {
                        $this->error('add oa_user_role 失败！');
                        return false;
                    }
                }
            }

            $this->success ( '修改' . $model ['title'] . '成功！', U ( 'lists?model=' . $model ['name'], $this->get_param ));

        } else {
            $emp_id = $_GET['id'];
            $emp = db_find('oa_employee', ['id'=>$emp_id]);
            $duty = db_find('oa_duty', ['id'=>$emp['duty_id']]);
            $dutyname = explode('_', $duty['name']);
            $dutyshortname = end($dutyname);
            $adminLvl = db_select('oa_emp_admin_level');
            $dept = db_find('oa_dept', ['id'=>$emp['dept_id']]);
            $chu_depts = db_select('oa_dept', ['dept_grade_id'=>2]);
            if($dept['dept_grade_id'] == 2) {
                $emp_chu_dept_id = $dept['id'];
                $emp_ke_depts = db_select('oa_dept', ['dept_grade_id'=>3, 'pid'=>$dept['id']]);
                array_unshift($emp_ke_depts, array('id'=>0, 'name'=>''));
            }
            else if($dept['dept_grade_id'] == 3) {
                $pdept = db_find('oa_dept', ['id'=>$dept['pid']]);
                $emp_chu_dept_id = $pdept['id'];
                $emp_ke_depts = db_select('oa_dept', ['dept_grade_id'=>3, 'pid'=>$pdept['id']]);
                array_unshift($emp_ke_depts, array('id'=>0, 'name'=>''));
                foreach ($emp_ke_depts as $i => $v) {
                    if($v['id'] == $dept['id'])
                        $emp_ke_depts[$i]['selected'] = 'selected';
                }
            }
            foreach ($chu_depts as $i => $v) {
                if($v['id'] == $emp_chu_dept_id)
                    $chu_depts[$i]['selected'] = 'selected';
            }
            array_unshift($chu_depts, array('id'=>0, 'name'=>''));

            foreach ($this->dutylist  as $i => $v) {
                $dutys[$i]['id'] = $i;
                $dutys[$i]['name'] = $v;
                if($dutyshortname == $v)
                    $dutys[$i]['selected'] = 'selected';
            }
            foreach ($adminLvl as $i => $v) {
                if($v['id'] == $emp['adminLvl_id'])
                    $adminLvl[$i]['selected'] = 'selected';
            }
            $sexsel[$emp['sex']] = 'selected';
            $emp['mobile_list'] = implode('; ', json_decode($emp['mobile_list'], true));
            $emp['birthday'] = date('Y-m-d', strtotime($emp['birthday']));

            $ke_depts = db_select('oa_dept', ['dept_grade_id'=>3]);
            $ke_depts = json_encode($ke_depts, JSON_UNESCAPED_UNICODE);
            $ke_depts = str_replace('"','&quot;', $ke_depts);

            $this->assign('chu_depts', $chu_depts);
            $this->assign('ke_depts', $ke_depts);
            $this->assign('emp_ke_depts', $emp_ke_depts);
            $this->assign('dutys', $dutys);
            $this->assign('adminLvl', $adminLvl);
            $this->assign('sexsel', $sexsel);
            $this->assign('data', $emp);
            $this->display();
        }
    }

    public function del(){
        $emp_id = $_GET['id'];
        if(empty($emp_id)) {
            $this->error('传入的员工ID为空！');
            return false;
        }
        if(($emp = db_find('oa_employee', ['id'=>$emp_id])) == NULL) {
            $this->error('找不到员工表！');
            return false;
        }
        $emp['is_left'] = 1;
        $emp['registered'] = 0;
        if(db_save('oa_employee', ['id'=>$emp_id], $emp) === false) {
            $this->error('保存员工表失败！');
            return false;
        }

        //del wp_user
        if(M('user')->where(['uid'=>$emp['userid']])->delete() == false) {
            myprint('delete user table', 'false');
        }

        //del oa_user_employee
        if(M('oa_user_employee')->where(['emp_id'=>$emp_id])->delete() == false) {
            myprint('delete oa_user_employee table', 'false');
        }

        //del apps_link
        if(M('apps_link')->where(['uid'=>$emp['userid']])->delete() == false) {
            myprint('delete apps_link table', 'false');
        }

        //del user_role
        if(M('oa_user_role')->where(['emp_id'=>$emp_id])->delete() == false) {
            myprint('delete oa_user_role table', 'false');
        }

        $this->success('删除成功！', U ( 'lists'/*'import?model=' . $this->model ['name'], $this->get_param */), 600);
    }

    public function resetpsd()
    {
        $emp_id = $_GET['id'];
        if (empty($emp_id)) {
            $this->error('传入的员工ID为空！');
            return false;
        }
        if(($emp = db_find('oa_employee', ['id'=>$emp_id])) == NULL) {
            $this->error('找不到员工表！');
            return false;
        }

        $map['uid'] = $emp['userid'];
        $user = M('user')->where($map)->find();
        if($user == NULL) {
            $this->error('找不到该员工对应的user表！');
            return false;
        }

        $user['password'] = think_weiphp_md5('123456');
        if(M('user')->where($map)->save($user) === false) {
            $this->error('保存user表员工初始密码失败！');
            return false;
        }

        $this->success('重置密码成功！', U ('lists'), 3);
    }
    public function import(){

        if (IS_POST) {
            $data['file'] = I('post.employees');
            $data['valid_date'] = date('y-m-d h:i:s', time());

            if (!intval($data['file'])) $this->error("数据文件未上传！");

            //这里是要用一个单独的表（模型）对导入行为进行记录！
            //$import_model = D('WxyClassCourseimport');
            //$import_model->add($data);

            if ($this->import_employee_data_from_excel($data['file'], $data['valid_date'], $data['comment'])) {
                $this->success('保存成功！', U ( 'lists'/*'import?model=' . $this->model ['name'], $this->get_param */), 600);
            }
        }
        else{
            $res['title'] = '员工信息表';
            $res['is_must'] = true;
            $res['is_show'] = 1;
            $res['name'] = 'employees';
            $res['type'] = 'file';
            $fields[] = $res;
            $post_url = addons_url ( 'OaSystem://OaEmployee/import');
            $this->assign('fields',$fields);
            $this->assign('post_url', $post_url);
            $this->assign('import_template','template_employees.xlsx');
            $this->display();

            //$this->display('import');
        }

    }

    private function import_employee_data_from_excel($file_id, $date = NULL, $comment = NULL) {
        if ($date == NULL) return false;
        $column = array (
            'A'=>'emp_no', //员工编号
            'B'=>'name',  //员工姓名
            'C'=>'mobile_list',   //手机
            'D'=>'dept_chu',  //处室
            'E'=>'dept_ke',   //科室
            'F'=>'duty',  //登录账号
            'G'=>'adminLvl',  //密码
            'K'=>'sex',  //性别
            'H'=>'idnum',      //身份证
            'N'=>'is_left',  //是否离职
        );

        $chu_dutys = array('处长', '副处长', '主任', '副主任', '组长', '副组长', '局长', '副局长');
        $ke_dutys = array('科长', '副科长', '主任', '副主任', '会长', '副会长', '主席', '副主席');

        $excel = importFormExcel($file_id, $column);
        if ($excel['status']) {
            if($this->checkExcel($excel['data']) == false)
                return false;
            foreach  ($excel['data'] as $row) {
                $row['emp_no'] = str_replace(' ', '', $row['emp_no']);
                $row['name'] = str_replace(' ', '', $row['name']);
                $row['dept_chu'] = str_replace(' ', '', $row['dept_chu']);
                $row['dept_ke'] = str_replace(' ', '', $row['dept_ke']);
                $row['duty'] = str_replace(' ', '', $row['duty']);
                if(empty($row['duty'])) $row['duty'] = '员工';

                if(($tmp = strstr($row['dept_chu'], '(', true)) != false ||
                    ($tmp = strstr($row['dept_chu'], '（', true)) != false){
                    $row['dept_chu'] = $tmp;
                }
                if(($tmp = strstr($row['dept_ke'], '(', true)) != false ||
                    ($tmp = strstr($row['dept_ke'], '（', true)) != false){
                    $row['dept_ke'] = $tmp;
                }

                //update oa_employee
                $dept_chu = db_find('oa_dept', ['name'=>$row['dept_chu']]);
                if(empty($row['dept_ke']))
                    $dept_id = $dept_chu['id'];
                else {
                    $dept_ke = db_find('oa_dept', ['name'=>$row['dept_ke'], 'pid'=>$dept_chu['id']]);
                    $dept_id = $dept_ke['id'];
                }

                if(empty($row['dept_ke']) && in_array($row['duty'], $chu_dutys))
                    $dutyname = $row['dept_chu'].'_'.$row['duty'];
                else if(!empty($row['dept_ke']) && in_array($row['duty'], $ke_dutys))
                    $dutyname = $row['dept_chu'].'_'.$row['dept_ke'].'_'.$row['duty'];
                else
                    $dutyname = $row['duty'];
                $duty = db_find('oa_duty', ['name'=>$dutyname]);
                $adminLvl = db_find('oa_emp_admin_level', ['name'=>$row['adminLvl']]);
                $mobile_array = explode(";", $row['mobile_list']);

                $data['appid'] = $this->appId;
                $data['emp_no'] = $row['emp_no'];
                $data['name'] = $row['name'];
                $data['idnum'] = $row['idnum'];
                $data['account'] = $row['emp_no'];
                $data['password'] = '123456';
                $data['sex'] = $row['sex'];
                $data['time'] = $date;
                $data['dept_id'] = $dept_id;
                $data['duty_id'] = $duty['id'];
                $data['adminLvl_id'] = $adminLvl['id'];
                $data['mobile_list'] = json_encode($mobile_array);
                $data['is_left'] = $row['is_left'];
                $res = D('OaEmployee')->addEmployee($data);
                if($res == false) {
                    $this->error('导入员工失败！可能是员工账号重复('.$data['account'].').');
                    return false;
                }

                //update oa_user_employee
                $employee = db_find('oa_employee', ['name'=>$data['name'], 'idnum'=>$data['idnum']]);
                $user_emp_data['appid'] = $this->appId;
                $user_emp_data['emp_id'] = $employee['id'];
                $user_emp_data['mobile_array'] = $mobile_array;
                $user_emp_data['time'] = $date;
                D('OaUserEmployee')->addUserEmployee($user_emp_data);

                //update oa_user_role
                $d = explode('兼', $dutyname);
                if(!empty($d[1])) {
                    if(empty($row['dept_ke']) && in_array($d[1], $chu_dutys))
                        $dutyname = $row['dept_chu'].'_'.$d[1];
                    else if(!empty($row['dept_ke']) && in_array($d[1], $ke_dutys))
                        $dutyname = $row['dept_chu'].'_'.$row['dept_ke'].'_'.$d[1];
                    $duty = db_find('oa_duty', ['name'=>$dutyname]);
                    if($duty != NULL) {
                        $data['duty_id'] = $duty['id'];
                    }
                }
                $dutyRoles = db_select('oa_role_duty', ['duty_id'=>$data['duty_id']]);
                foreach ($dutyRoles as $v) {
                    $user_role['appid'] = $this->appId;
                    $user_role['emp_id'] = $employee['id'];
                    $user_role['role_id'] = $v['role_id'];
                    $user_role['assigned_by'] = 0;
                    $res = M('OaUserRole')->where(array('emp_id'=>$employee['id'],'role_id'=>$v['role_id']))->find();
                    if (empty($res)){
                        if(M('oa_user_role')->add($user_role) == false) {
                            $this->error('add oa_user_role 失败！');
                            return false;
                        }
                    }
                }
            }
            return true;
        }
        else {
            $this->error('请检查文件格式');
            return false;
        }
    }

    private function checkExcel($data) {
        foreach ($data as $row) {
            $row['emp_no'] = str_replace(' ', '', $row['emp_no']);
            $row['name'] = str_replace(' ', '', $row['name']);
            $row['dept_chu'] = str_replace(' ', '', $row['dept_chu']);
            $row['dept_ke'] = str_replace(' ', '', $row['dept_ke']);
            $row['duty'] = str_replace(' ', '', $row['duty']);
            if(empty($row['duty'])) $row['duty'] = '员工';

            if(($tmp = strstr($row['dept_chu'], '(', true)) != false ||
                ($tmp = strstr($row['dept_chu'], '（', true)) != false){
                $row['dept_chu'] = $tmp;
            }
            if(($tmp = strstr($row['dept_ke'], '(', true)) != false ||
                ($tmp = strstr($row['dept_ke'], '（', true)) != false){
                $row['dept_ke'] = $tmp;
            }

            if(($dept_chu = db_find('oa_dept', ['name'=>$row['dept_chu']])) == NULL) {
                $this->error($row['name'].' 的 处室 ('.$row['dept_chu'].') 在后台查找不到，请检查！');
                return false;
            }
            if(!empty($row['dept_ke'])) {
                if (($dept_ke = db_find('oa_dept', ['name' => $row['dept_ke'], 'pid' => $dept_chu['id']])) == NULL) {
                    $this->error($row['name'] . ' 的 科室 (' . $row['dept_ke'] . ') 在后台查找不到，请检查！');
                    return false;
                }
            }

            $chu_dutys = array('处长', '副处长', '主任', '副主任', '组长', '副组长', '局长', '副局长');
            $ke_dutys = array('科长', '副科长', '主任', '副主任', '会长', '副会长','主席', '副主席');
            if(empty($row['dept_ke']) && in_array($row['duty'], $chu_dutys))
                $dutyname = $row['dept_chu'].'_'.$row['duty'];
            else if(!empty($row['dept_ke']) && in_array($row['duty'], $ke_dutys))
                $dutyname = $row['dept_chu'].'_'.$row['dept_ke'].'_'.$row['duty'];
            else
                $dutyname = $row['duty'];
            $duty = db_find('oa_duty', ['name'=>$dutyname]);
            if($duty == NULL) {
                $this->error($row['name'].' 的 职务 ('.$dutyname.') 在后台查找不到，请检查！');
                return false;
            }

            if(!db_find('oa_emp_admin_level', ['name'=>$row['adminLvl']])) {
                $this->error($row['name'].' 的 行政级别 ('.$row['adminLvl'].') 在后台查找不到，请检查！');
                return false;
            }
            if(!db_find('oa_role_duty', ['duty_id'=>$duty['id']])) {
                $this->error($row['name'].' 的 职务角色关系 ('.$row['duty'].') 在后台查找不到，请检查！');
                return false;
            }
        }
        return true;
    }

    public function export(){
        $employees = M('OaEmployee')->select();
        $data = array();
        $headArr = array("员工编号","员工姓名","性别","出生年月日","身份证号码","登录名","密码","部门","职务","行政级别	","办公室电话","手机","是否离职(0:在职,1:离职)");
        $data[] = $headArr;
        foreach ($employees as $employee){
            $tmp = array();
            $tmp[] = $employee['emp_no'];
            $tmp[] = $employee['name'];
            $tmp[] = $employee['sex'];
            $tmp[] = $employee['birthday'];
            $tmp[] = $employee['idnum'];
            $tmp[] = $employee['account'];
            $tmp[] = $employee['password'];
            $tmp[] = M('OaDept')->where(array('id'=>$employee['dept_id']))->getField('name');
            $tmp[] = M('OaDuty')->where(array('id'=>$employee['duty_id']))->getField('name');
            $tmp[] = M('OaEmpAdminLevel')->where(array('id'=>$employee['adminLvl_id']))->getField('name');
            $tmp[] = $employee['office_tel'];
            $tmp[] = implode(';',json_decode($employee['mobile_list'],true));
            $tmp[] = $employee['is_left'];
            $data[] = $tmp;
        }
        $filename = "员工数据表";
        outExcel($data,$filename);
    }
}
